<script setup lang="ts">

import {onMounted, reactive, ref} from "vue"
import type {HouseType} from "@/type/House";
import type {GetType} from "@/type/GetType";
import {deleteData, getAllHouse, getAllUsers, post, put} from "@/net";
import {Delete, EditPen} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox, ElTable} from "element-plus";

// 状态变量
const dialogAddVisible = ref(false);
const dialogUpdateVisible = ref(false);
// 功能函数
const fetchHouseListAndRefresh = () => {
  getAllHouseData();
};
const handleOperationResult = (success: boolean) => {
  if (success) {
    fetchHouseListAndRefresh();
  }
};

const closeUpdataDialog = () => {
  dialogUpdateVisible.value = false;
};
const closeAddDialog = () => {
  dialogAddVisible.value = false;
};

const handleAddSelectChange = (um: string) => {
  const index = username.findIndex(user => user.username === um);
  if (um in username){
    addHouseForm.uid = username[index].uid;
    addHouseForm.username = username[index].username;
  }
}
// 增加房屋
let addHouseForm = reactive<HouseType>({
  house_id: 0,
  uid: 0,
  address: '',
  state: '',
  remark: '',
  username: ''
});
const submitAddHouse = () => {
  post('api/house/add', addHouseForm, () => {
    ElMessage.success("添加成功");
    fetchHouseListAndRefresh();
    handleOperationResult(true);
  }, () => {
    ElMessage.warning("添加失败")
    fetchHouseListAndRefresh();
    closeAddDialog();
  }, () => {
    ElMessage.error("发生了错误");
    fetchHouseListAndRefresh();
    closeAddDialog();
  })
}

// 删除房屋
const handleDeleteHouse = (index: number, row: HouseType) => {
  ElMessageBox.confirm("你要删除房屋吗?", "提示", {
    icon: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    deleteData("api/house/delete", {house_id: row.house_id}, () => {
      ElMessage.success("删除成功");
      handleOperationResult(true);
    }, () => {
      ElMessage.warning("删除失败,")
    }, () => {
      ElMessage.error("删除失败")
    });
  }).catch((err) => {
    ElMessage.error(err)
  })
};
// 修改房屋
let updateHouseForm = reactive<HouseType>({
  house_id: 0,
  uid: 0,
  address: '',
  state: '',
  remark: '',
  username: ''
});

const handleUpdateHouse = (row: Partial<typeof updateHouseForm>) => {
  Object.keys(row).forEach(key => {
    if (updateHouseForm.hasOwnProperty(key)) {
      (updateHouseForm as any)[key] = row[key];  // 或者使用更安全的类型断言或类型守卫
    }
  });
  dialogUpdateVisible.value = true;
};

const submitUpdate = async () => {
  const index = houseData.findIndex(item => item.house_id === updateHouseForm.house_id);
  try {
    let house = {
      house_id: updateHouseForm.house_id,
      uid: updateHouseForm.uid,
      address: updateHouseForm.address,
      state: updateHouseForm.state,
      remark: updateHouseForm.remark,
      username: updateHouseForm.username
    }
    await put("api/house/update", house, (res: any) => {
      houseData[index] = updateHouseForm;
      ElMessage.success(res.message);
      handleOperationResult(true);
    })
  } catch (err) {
    ElMessage.warning("修改失败");
  }
}
// Method Not Allowed
// 获取房屋
let houseData: HouseType[] = reactive([]);

const getAllHouseData = async () => {
  try {
    const res: GetType = await getAllHouse('/api/house/getAll');
    houseData.splice(0, houseData.length, ...res.message);
  } catch (e) {
    console.log(e)
  }
};

// 生命周期函数
onMounted(() => {
  getAllHouseData();
  getAllUser_name();

});
// 常量


// 用户变量
interface UserNameType {
  username: string;
  uid: number;
}

const username = reactive<UserNameType[]>([]);
const getAllUser_name = async () => {
  try {
    const res: GetType = await getAllUsers('/api/user/getAllName');
    username.splice(0, username.length, ...res.message.filter((user: any) => user.name !== null));
  } catch (e) {
    console.log(e)
  }
};

const stateOptions = [
  {
    label: '使用中',
    value: '使用中'
  },
  {
    label: '未使用',
    value: '未使用'
  }

];

</script>

<template>
  <div style="display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: 10px">
    <div>
      <span>信息管理 > 房屋信息</span>
    </div>
    <div style="margin-right: 60px">
      <el-button type="primary" @click="dialogAddVisible = true">添加房屋</el-button>
    </div>
  </div>

  <el-table ref="table" :data="houseData" style="width: 100%"
            height="70vh" border
  >
    <el-table-column type="index" label="序号"/>
    <el-table-column prop="username" label="用户名"/>
    <el-table-column prop="address" label="地址"/>
    <el-table-column prop="state" label="使用情况"/>
    <el-table-column prop="remark" label="备注"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button name="update" @click="handleUpdateHouse(scope.row)" type="warning" :icon="EditPen" circle/>
        <el-button name="delete" id="delete_button" plain @click="handleDeleteHouse(scope.$index,scope.row)" type="danger" :icon="Delete"
                   circle/>
      </template>

    </el-table-column>
  </el-table>

  <el-dialog
      title="添加房屋信息"
      :model-value="dialogAddVisible"
      width="50%"
      @close="closeAddDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             style="width: 500px;"
             v-model="addHouseForm"
    >
      <el-form-item label="用户名" :required="true" style="width: 240px">
        <el-select v-model="addHouseForm.username"
                   placeholder="请选择"
                   style="width: 240px"
                   prop="username"
                   @change="handleAddSelectChange"
        >
          <el-option
              v-for="user in username"
              :key="user.uid"
              :label="user.username"
              :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" :required="true" style="width: 300px">
        <el-input v-model="addHouseForm.address" prop="name"></el-input>
      </el-form-item>
      <el-form-item label="使用情况" :required="true">
        <el-select v-model="addHouseForm.state"
                   placeholder="请选择"
                   style="width: 220px"
                   prop="gender">
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" style="width: 350px;">
        <el-input type="textarea" v-model="addHouseForm.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitAddHouse">确定</el-button>
        <el-button @click="closeAddDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  修改房屋  -->
  <el-dialog
      title="修改房屋信息"
      :model-value="dialogUpdateVisible"
      width="50%"
      @close="closeUpdataDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             style="width: 500px;"
    >
      <el-form-item label="用户名" style="width: 20vw">
        <el-input disabled v-model="updateHouseForm.username" prop="name"></el-input>
      </el-form-item>
      <el-form-item label="地址" :required="true" style="width: 20vw">
        <el-input v-model="updateHouseForm.address" prop="name"></el-input>
      </el-form-item>
      <el-form-item label="使用情况" :required="true">
        <el-select v-model="updateHouseForm.state"
                   placeholder="请选择"
                   style="width: 20vw"
                   prop="gender">
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" style="width: 25vw;">
        <el-input type="textarea" v-model="updateHouseForm.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpdate">确定</el-button>
        <el-button @click="closeUpdataDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>

</style>